package com.gmail.bloim.serg.testrunner;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * User: Администратор
 * Date: 25.04.13
 * Time: 13:58
 */
public class SimpleTestResultComparator implements TestResultComparator {
    @Override
    public boolean judge(Test test, byte[] res) throws IOException {
        InputStream expected = test.createStdOut();
        InputStream real = new ByteArrayInputStream(res);
        return compareInputStreams(expected, real);
    }

    private boolean compareInputStreams(InputStream in1, InputStream in2) throws IOException {
        boolean equal = false;
        try {
            while (true) {
                int available1 = in1.available();
                int available2 = in2.available();
                if (available1 == 0 && available2 == 0) {
                    equal = true;
                    break;
                }
                if (available1 == 0 || available2 == 0) break;
                int v1 = in1.read();
                int v2 = in2.read();
                if (v1 != v2)
                    break;
            }
        } finally {
            try {
                in1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return equal;
    }
}
